
#include "addressbook.h"
#include "adddialog.h"
#include "treeview.h"

AddressBook::AddressBook(QWidget *parent)
    : QWidget(parent)
{
	ui.setupUi(this);
}

AddressBook::~AddressBook()
{

}

void AddressBook::on_AddButton_clicked()
{
    AddDialog dialog(this);
    if (dialog.exec())
    {
        QString name = dialog.name();
        QString email = dialog.email();

        if (!name.isEmpty() && !email.isEmpty())
        {
			QStringList *Item = new QStringList();
			Item->append(name);
			Item->append(email);

			AddressList.append(Item);

        	QListWidgetItem *item = new QListWidgetItem(name, ui.AddressList);
            item->setData(Qt::UserRole, email);
            ui.AddressList->setCurrentItem(item);
        }
    }

}

void AddressBook::on_AddressList_currentItemChanged()
{
    QListWidgetItem *curItem = ui.AddressList->currentItem();

        if (curItem)
        {
                ui.NameLabel->setText("Name: " + curItem->text());
                ui.EmailLabel->setText("Email: " + curItem->data(Qt::UserRole).toString());
        }
        else
        {
                ui.NameLabel->setText("<No item selected>");
                ui.EmailLabel->clear();
        }
}

void AddressBook::on_DeleteButton_clicked()
{
    QListWidgetItem *curItem = ui.AddressList->currentItem();

        if (curItem)
        {
                int row = ui.AddressList->row(curItem);
                ui.AddressList->takeItem(row);
                delete curItem;

                if (ui.AddressList->count() > 0)
                        ui.AddressList->setCurrentRow(0);
                else
                        on_AddressList_currentItemChanged();
        }
}

void AddressBook::on_TreeButton_clicked()
{
    TreeView dialog(this);
	dialog.SetList(AddressList);
    dialog.exec();
}

